package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转一下servletRequest，servletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String path = request.getRequestURI();
        log.info("请求路径：{}", path);
        //判断是否是LOGIN
        if (path.contains("login")) {
            //放行
            filterChain.doFilter(request, response);
        }
        //在请求头里面获取token
        String token = request.getHeader("token");
        //判断token的健壮性，token为空
        if (token == null || token.isEmpty()) {
            log.info("token为空");
            response.setStatus(401);
            return;
        }
        //解析token，判断token是否非法
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("token解析成功");
            Integer id = claims.get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(id);
        }
        catch (Exception e) {
            log.info("token为非法,解析失败");
            response.setStatus(401);
            return;

        }
        //放行
        filterChain.doFilter(request, response);
        /**
         * 释放资源
         */
        log.info("释放资源");
        CurrentUserHoler.removeCurrentUser();
    }
}
